package com.spzx.auth.service.impl;

import com.spzx.auth.form.H5RegisterBody;
import com.spzx.auth.form.LoginBody;
import com.spzx.auth.service.H5UserService;
import com.spzx.auth.service.SysPasswordService;
import com.spzx.auth.service.SysRecordLogService;
import com.spzx.common.core.constant.CacheConstants;
import com.spzx.common.core.constant.Constants;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.constant.UserConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.enums.UserStatus;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.text.Convert;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.ip.IpUtils;
import com.spzx.common.redis.service.RedisService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.system.api.domain.SysUser;
import com.spzx.system.api.model.LoginUser;
import com.spzx.user.api.domain.UpdateUserLogin;
import com.spzx.user.api.domain.UserInfo;
import com.spzx.user.api.service.RemoteUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class H5UserServiceImpl implements H5UserService {
    @Autowired
    private RemoteUserInfoService remoteUserInfoService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SysRecordLogService recordLogService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private SysPasswordService passwordService;


    @Override
    public void register(H5RegisterBody h5RegisterBody) {
        //获取请求数据
        String username = h5RegisterBody.getUsername();
        String password = h5RegisterBody.getPassword();
        String nickName = h5RegisterBody.getNickName();
        String code = h5RegisterBody.getCode();
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password,code))
        {
            throw new ServiceException("用户/密码/验证码必须填写");
        }
        if (username.length()!=11 )
        {
            throw new ServiceException("手机号必须是11位");
        }
        if ((password.length() < UserConstants.PASSWORD_MIN_LENGTH+1
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH-2))
        {
            throw new ServiceException("密码长度必须在6到18个字符之间");
        }

        //从Redis中获取验证码
        String redisCode = stringRedisTemplate.opsForValue().get("h5:" + username);

        //判断验证码是否正确
        if (!code.equals(redisCode)){
            //验证码不正确
            throw new ServiceException("验证码不正确");
        }

        //将Redis中的验证码删除
       // stringRedisTemplate.delete("h5"+username);

        // 注册用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        //如果有昵称就是昵称没用昵称就是用户名
        userInfo.setNickName(StringUtils.hasText(nickName)?nickName:username);
        userInfo.setPassword(SecurityUtils.encryptPassword(password));
        userInfo.setSex(0);
        userInfo.setStatus(1);
        userInfo.setPhone(username);
        R<?> registerResult = remoteUserInfoService.register(userInfo, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
        recordLogService.recordLogininfor(username, Constants.REGISTER, "注册成功");

    }

    @Override
    public LoginUser login(LoginBody form) {
        //获取用户名和密码
        String username = form.getUsername();
        String password = form.getPassword();

        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户/密码必须填写");
            throw new ServiceException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH+1
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH-2)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() !=11)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
            throw new ServiceException("用户名不在指定范围");
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<UserInfo> userResult = remoteUserInfoService.getUserInfoByUsername(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + username + " 不存在");
        }

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        //获取用户信息
        UserInfo userInfo = userResult.getData();
        if (UserStatus.DELETED.getCode().equals(userInfo.getDelFlag()))
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (userInfo.getStatus()==0)
        {
            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        //创建 LoginUser对象
        LoginUser loginUser = new LoginUser();
        loginUser.setUserid(userInfo.getId());
        loginUser.setUsername(username);
        loginUser.setPassword(userInfo.getPassword());

        //验证秘法是否正确
        passwordService.validate(loginUser, password);

        //创建UpdateUserLogin
        UpdateUserLogin updateUserLogin = new UpdateUserLogin();
        //设置主键
        updateUserLogin.setUserId(userInfo.getId());
        updateUserLogin.setLastLoginIp(updateUserLogin.getLastLoginIp());
        updateUserLogin.setLastLoginTime(userInfo.getLastLoginTime());

        //远程调用
        remoteUserInfoService.updateUserLogin(updateUserLogin,SecurityConstants.INNER);

        //记录登录日志
        recordLogService.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功");
        return loginUser;

    }
}
